﻿using System;

namespace movie.tool.library.utils
{
    /// <summary>
    /// 整数的工具方法
    /// </summary>
    public class NumberUtils
    {
        /// <summary>
        /// 安全地把字符串转为整数
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="defaultValue">不能转换时的默认值</param>
        /// <returns>整数</returns>
        public static int SafeStringToInt(string str, int defaultValue)
        {
            int v = defaultValue;
            try
            {
                if (!int.TryParse(str, out v))
                {
                    v = defaultValue;
                }
            }
            catch (Exception)
            {
                v = defaultValue;
            }

            return v;
        }

        /// <summary>
        /// 以指定的分隔符，将字符串转换为整数数组
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="spliter">字符串分隔符</param>
        /// <returns>转换后的整数数组，如果转换没有成功返回null</returns>
        public static int[] StringToIntArray(string str, char spliter)
        {
            if (string.IsNullOrWhiteSpace(str) || string.IsNullOrWhiteSpace(spliter.ToString()))
            {
                return null;
            }
            try
            {
                string[] strArray = str.Split(spliter);
                int[] ints = new int[strArray.Length];
                int index = 0;
                foreach (string s in strArray)
                {
                    ints[index++] = SafeStringToInt(s, int.MaxValue);
                }
                return ints;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
